import fetch from "dva/fetch";

const baseURL = "http://mocktest.com:3001";

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

const defaultOptions = {
  method: "post"
  // headers: {
  //   "Content-Type": "application/json"
  // }
};

export default function request(url, params = {}, options = {}) {
  url = /^http/.test(url) ? url : baseURL + url;
  options = {
    ...defaultOptions,
    ...options,
    body: JSON.stringify(params)
  };
  if (options.method === "get") {
    delete options.body;
  }
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(res => res)
    .catch(err => ({ code: 5000, res: "FAIL" }));
}
